<template>
  <div>
    <el-upload
            class="addicon"
            :action="$uploadImg"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-progress="handleProgress"
            accept=".doc,.docx,.xls,.xlsx,.rar,.zip,.7z,.jpg,.jpeg,.png,.mp4,.pdf"
            :before-upload="beforeAvatarUpload">
      <img v-if="pic" :src="pic">
      <viewerModle type="1" :imgSrc="pic" v-if="pic"></viewerModle>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <progressDialog :visible.sync="progressVisible" :progressPercent="progressPercent"></progressDialog>
  </div>
</template>

<script>
  import api from '@/utils/api.js'
  import progressDialog from '@/components/dialog/progressDialog.vue'
  export default {
    components: {
      progressDialog
    },
    props: ['imgsrc'],
    name: 'uploadimg',
    data () {
      return {
        progressVisible: false,
        progressPercent: 0,
        pic: this.imgsrc
      }
    },
    watch: {
      imgsrc () {
        this.pic = this.imgsrc
      }
    },
    methods: {
      handleSuccess (response) {
        let this_ = this
        this.pic = response.data.name
        this.$emit('getImgSrc', response.data.name)
        setTimeout(() => {
          this_.progressVisible = false
          this_.progressPercent = 0
        }, 700)
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return
        }
        this.progressVisible = true
      },
      handleProgress () {
        this.progressPercent = parseInt(event.percent)
      }
    }
  }
</script>
